package com.example.managemyself.util;

import android.content.Context;
import android.util.Log;

import androidx.lifecycle.LiveData;

import com.example.managemyself.data.database.AppDatabase;
import com.example.managemyself.data.database.UserApiKeyDao;
import com.example.managemyself.data.model.UserApiKey;
import com.example.managemyself.data.model.User;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * API密钥管理器
 * 负责管理用户的各种API密钥
 */
public class ApiKeyManager {
    
    private static final String TAG = "ApiKeyManager";
    
    public static final String API_TYPE_DEEPSEEK = "deepseek";
    public static final String API_TYPE_OPENAI = "openai";
    public static final String API_TYPE_WEATHER = "weather";
    public static final String API_TYPE_ALMANAC = "almanac";
    
    private static ApiKeyManager instance;
    private final UserApiKeyDao apiKeyDao;
    private final ExecutorService executorService;
    private final UserManager userManager;
    
    private ApiKeyManager(Context context) {
        AppDatabase database = AppDatabase.getInstance(context);
        apiKeyDao = database.userApiKeyDao();
        executorService = Executors.newSingleThreadExecutor();
        userManager = UserManager.getInstance();
    }
    
    public static synchronized ApiKeyManager getInstance(Context context) {
        if (instance == null) {
            instance = new ApiKeyManager(context.getApplicationContext());
        }
        return instance;
    }
    
    /**
     * 获取当前用户ID
     */
    private String getCurrentUserId() {
        User currentUser = userManager.getCurrentUser();
        return currentUser != null ? String.valueOf(currentUser.getId()) : null;
    }
    
    /**
     * 保存或更新API密钥
     */
    public void saveApiKey(String apiType, String apiKey, String apiName, SaveCallback callback) {
        String currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            if (callback != null) callback.onError("用户未登录");
            return;
        }
        
        executorService.execute(() -> {
            try {
                // 先停用同类型的其他密钥
                apiKeyDao.deactivateApiKeysByType(currentUserId, apiType);
                
                // 检查是否已存在相同的密钥
                UserApiKey existingKey = apiKeyDao.getUserApiKeyByTypeSync(currentUserId, apiType);
                
                if (existingKey != null && apiKey.equals(existingKey.getApiKey())) {
                    // 重新激活现有密钥
                    existingKey.setActive(true);
                    apiKeyDao.update(existingKey);
                } else {
                    // 创建新的API密钥记录
                    UserApiKey newApiKey = new UserApiKey(currentUserId, apiType, apiKey, apiName);
                    newApiKey.setDescription("用户添加的" + apiName + "密钥");
                    apiKeyDao.insert(newApiKey);
                }
                
                if (callback != null) callback.onSuccess("API密钥保存成功");
                Log.i(TAG, "API密钥保存成功: " + apiType);
                
            } catch (Exception e) {
                Log.e(TAG, "保存API密钥失败", e);
                if (callback != null) callback.onError("保存失败: " + e.getMessage());
            }
        });
    }
    
    /**
     * 获取用户的DeepSeek API密钥
     */
    public void getDeepSeekApiKey(ApiKeyCallback callback) {
        String currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            callback.onResult(null);
            return;
        }
        
        executorService.execute(() -> {
            try {
                UserApiKey apiKey = apiKeyDao.getUserDeepSeekKeySync(currentUserId);
                callback.onResult(apiKey != null ? apiKey.getApiKey() : null);
            } catch (Exception e) {
                Log.e(TAG, "获取DeepSeek API密钥失败", e);
                callback.onResult(null);
            }
        });
    }
    
    /**
     * 同步获取DeepSeek API密钥
     */
    public String getDeepSeekApiKeySync() {
        String currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return null;
        }
        
        try {
            UserApiKey apiKey = apiKeyDao.getUserDeepSeekKeySync(currentUserId);
            return apiKey != null ? apiKey.getApiKey() : null;
        } catch (Exception e) {
            Log.e(TAG, "同步获取DeepSeek API密钥失败", e);
            return null;
        }
    }
    
    /**
     * 获取特定类型的API密钥
     */
    public void getApiKey(String apiType, ApiKeyCallback callback) {
        String currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            callback.onResult(null);
            return;
        }
        
        executorService.execute(() -> {
            try {
                UserApiKey apiKey = apiKeyDao.getUserApiKeyByTypeSync(currentUserId, apiType);
                callback.onResult(apiKey != null ? apiKey.getApiKey() : null);
            } catch (Exception e) {
                Log.e(TAG, "获取API密钥失败: " + apiType, e);
                callback.onResult(null);
            }
        });
    }
    
    /**
     * 获取用户的所有API密钥
     */
    public LiveData<List<UserApiKey>> getUserApiKeys() {
        String currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return null;
        }
        return apiKeyDao.getUserApiKeys(currentUserId);
    }
    
    /**
     * 获取用户的激活API密钥
     */
    public LiveData<List<UserApiKey>> getActiveApiKeys() {
        String currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return null;
        }
        return apiKeyDao.getActiveApiKeys(currentUserId);
    }
    
    /**
     * 删除API密钥
     */
    public void deleteApiKey(int apiKeyId, DeleteCallback callback) {
        executorService.execute(() -> {
            try {
                apiKeyDao.deleteById(apiKeyId);
                if (callback != null) callback.onSuccess("API密钥删除成功");
                Log.i(TAG, "API密钥删除成功: " + apiKeyId);
            } catch (Exception e) {
                Log.e(TAG, "删除API密钥失败", e);
                if (callback != null) callback.onError("删除失败: " + e.getMessage());
            }
        });
    }
    
    /**
     * 停用API密钥
     */
    public void deactivateApiKey(int apiKeyId, UpdateCallback callback) {
        executorService.execute(() -> {
            try {
                apiKeyDao.updateActiveStatus(apiKeyId, false);
                if (callback != null) callback.onSuccess("API密钥已停用");
                Log.i(TAG, "API密钥已停用: " + apiKeyId);
            } catch (Exception e) {
                Log.e(TAG, "停用API密钥失败", e);
                if (callback != null) callback.onError("停用失败: " + e.getMessage());
            }
        });
    }
    
    /**
     * 激活API密钥
     */
    public void activateApiKey(int apiKeyId, String apiType, UpdateCallback callback) {
        String currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            if (callback != null) callback.onError("用户未登录");
            return;
        }
        
        executorService.execute(() -> {
            try {
                // 先停用同类型的其他密钥
                apiKeyDao.deactivateApiKeysByType(currentUserId, apiType);
                // 激活指定密钥
                apiKeyDao.updateActiveStatus(apiKeyId, true);
                
                if (callback != null) callback.onSuccess("API密钥已激活");
                Log.i(TAG, "API密钥已激活: " + apiKeyId);
            } catch (Exception e) {
                Log.e(TAG, "激活API密钥失败", e);
                if (callback != null) callback.onError("激活失败: " + e.getMessage());
            }
        });
    }
    
    /**
     * 检查用户是否有DeepSeek API密钥
     */
    public void hasDeepSeekApiKey(HasKeyCallback callback) {
        String currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            callback.onResult(false);
            return;
        }
        
        executorService.execute(() -> {
            try {
                int count = apiKeyDao.hasApiKeyOfType(currentUserId, API_TYPE_DEEPSEEK);
                callback.onResult(count > 0);
            } catch (Exception e) {
                Log.e(TAG, "检查DeepSeek API密钥失败", e);
                callback.onResult(false);
            }
        });
    }
    
    /**
     * 清理用户的所有API密钥
     */
    public void clearUserApiKeys(DeleteCallback callback) {
        String currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            if (callback != null) callback.onError("用户未登录");
            return;
        }
        
        executorService.execute(() -> {
            try {
                apiKeyDao.deleteAllUserApiKeys(currentUserId);
                if (callback != null) callback.onSuccess("所有API密钥已清理");
                Log.i(TAG, "用户API密钥已清理: " + currentUserId);
            } catch (Exception e) {
                Log.e(TAG, "清理API密钥失败", e);
                if (callback != null) callback.onError("清理失败: " + e.getMessage());
            }
        });
    }
    
    // 回调接口定义
    public interface SaveCallback {
        void onSuccess(String message);
        void onError(String error);
    }
    
    public interface ApiKeyCallback {
        void onResult(String apiKey);
    }
    
    public interface DeleteCallback {
        void onSuccess(String message);
        void onError(String error);
    }
    
    public interface UpdateCallback {
        void onSuccess(String message);
        void onError(String error);
    }
    
    public interface HasKeyCallback {
        void onResult(boolean hasKey);
    }
} 